import React from 'react';
import ReactDOM from 'react-dom';
import HooksRedux from './hooks-redux';

const { Provider, store } = HooksRedux({
  initialState: {
    name: '小王',
    age: 18,
  },
});

function actionOfIncrease() {
  return {
    type: 'init', // increase
    reducer: (state) => {
      return { ...state, age: state.age + 1 };
    },
  };
}

function actionOfDecrement() {
  return {
    type: 'decrement',
    reducer: (state) => {
      return { ...state, age: state.age - 1 };
    },
  };
}

// sleep 函数
function sleep(c = 18, ts = 500) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(++c);
    }, ts);
  });
}

// 异步
const actionAsyncOfIncrease = () => async (dispatch, ownState) => {
  const age = await sleep(ownState.age, 100);
  dispatch({
    type: 'increase',
    reducer(state) {
      return {
        ...state,
        age,
      };
    },
  });
};

function Button() {
  function handleIncrease() {
    // store.dispatch({
    //   type: 'init',
    // });
    store.dispatch(actionOfIncrease());
  }

  function handleDecrement() {
    store.dispatch(actionOfDecrement());
  }

  function handleAsyncIncrease() {
    store.dispatch(actionAsyncOfIncrease());
  }

  return (
    <>
      <button onClick={handleIncrease}>点击增加</button>
      <button onClick={handleDecrement}>点击减少</button>
      <button onClick={handleAsyncIncrease}>async点击增加</button>
    </>
  );
}

function Page() {
  const state = store.useContext();

  return (
    <>
      <div>{state.name}</div>
      <div>{state.age}</div>
      <Button></Button>
    </>
  );
}

function App() {
  return (
    <Provider>
      <Page />
    </Provider>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
